//
//  MainViewController.swift
//  微博Swift
//
//  Created by apple on 15/9/21.
//  Copyright © 2015年 cc. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {
    
    // MARK: -按钮监听方法
    // 这里不能单纯的使用 private ，运行循环无法找到方法，造成崩溃
    // 使用 @objc 在编译的时候会对函数做特殊处理，保证运行循环能
    // 通过消息机制找到该方法
    @objc func addBtnClick(){
        print("addBtnClick")
    }
    
    // MARK: - 设置控制器
    override func viewDidLoad() {
        super.viewDidLoad()
        // 添加控制器
        addChildViewControllers()
        creatAddBtn()

    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        tabBar.bringSubviewToFront(addBtn)
    }

    
    // MARK: - 添加加号按钮
    private func creatAddBtn(){
        
        tabBar.addSubview(addBtn)
        
        let count = self.viewControllers!.count
        let width = tabBar.bounds.width / CGFloat(count) - 1 // 填充按钮间隙
        
        // 向两边缩进，形成一个中心点相同的矩形
        addBtn.frame = CGRectInset(tabBar.bounds, width*2, 0)

    }
    
    // MARK: -添加所有子控制器
    private func addChildViewControllers() {
        
        addChildViewController(HomeViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewController(DiscoverViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileViewController(), title: "我", imageName: "tabbar_profile")
        
    }

    private func addChildViewController(vc: UIViewController,title: String, imageName: String) {
        //  设置tabBarItem
        vc.title = title
        
//        tabBar.tintColor = UIColor.orangeColor()
        
        vc.tabBarItem.image = UIImage(named: imageName)
        
        addChildViewController(UINavigationController(rootViewController: vc))

    }
    
    // MARK: -懒加载
    private lazy var addBtn: UIButton = {
        
        let btn: UIButton = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
        btn.addTarget(self, action: "addBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
        
    }()
    
}
